package com.sfx.concurrent.demo.concurrent.pattern.MessageQueue;

import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;

@Slf4j(topic = "c.MessageQueue")
public class MessageQueue {

    //用一个集合来生产和消费消息-->从尾部生产,从头部消费
    private LinkedList<Message> list = new LinkedList<>();
    //消息队列容量
    private int capacity;

    public MessageQueue(int capacity) {
        this.capacity = capacity;
    }

    //获取消息-->消费者
    public Message get(){
        //如果消息队列为空就一直等待不能消费
        synchronized (list) {
            while(list.isEmpty()){
                try {
                    log.debug("消息队列已空,消费者阻塞");
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //消费掉
            Message message = list.removeFirst();
            log.debug("已消费消息");
            list.notifyAll();
            return message;
        }
    }

    //存入消息-->生产者
    public void take(Message message){
        synchronized (list) {
            while(list.size()==capacity) {
                try {
                    log.debug("消息队列已满,生产者阻塞");
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.addLast(message);
            log.debug("已生产消息");
            list.notifyAll();
        }
    }
}